<style>
    .avatar-uploader {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 160px
    }

    .avatar-uploader :hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 160px;
      height: 160px;
      line-height: 160px;
      text-align: center;
    }

    .avatar {
      width: 160px;
      height: 160px;
      display: block;
      object-fit: cover; /* 裁剪图片保持比例，可选值：contain（缩放适应）、cover（裁剪填充） */
      border-radius: 4px; /* 圆角（可选） */
    }
</style>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="广告标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入广告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入活动内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:ad:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ad:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ad:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:ad:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="adList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="广告ID" align="center" prop="id" />
      <el-table-column label="广告标题" align="center" prop="name" />
      <el-table-column label="活动链接" align="center" prop="link" />
      <el-table-column label="广告图片" align="center" prop="url" width="100">
              <template slot-scope="scope">
                <image-preview :src="scope.row.url" :width="50" :height="50"/>
              </template>
            </el-table-column>
      <el-table-column label="广告位置" align="center" prop="position" >
      <template slot-scope="scope">
          {{scope.row.position==1 ? "首页":"分类"}}
        </template>
      </el-table-column>
      <el-table-column label="活动内容" align="center" prop="content" />
      <el-table-column label="是否启动" align="center" prop="enabled" >
        <template slot-scope="scope">
          {{scope.row.enabled==1 ? "启用":"不启用"}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:ad:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ad:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告标题" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="广告内容" prop="content">
          <el-input v-model="form.content"/>
        </el-form-item>
        <!-- <el-form-item label="广告图片" prop="url">
          <el-upload
            class="avatar-uploader"
            action="https://http://localhost/popularize/ad"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.url" :src="form.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->

        <el-form-item label="广告图片" prop="url">
          <el-upload v-model="form.url" :file-list="fileList" :limit="1"  :before-upload="(file) => handleImageChange(file, 'url')"
            :show-file-list="false" class="avatar-uploader" action="#">
            <!-- 自定义上传按钮或图片预览 -->
            <img v-if="form.url" :src="form.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

          <el-form-item label="广告位置">
            <el-select v-model="form.position" placeholder="请选择广告位置" >
              <el-option
                v-for="isho in positions"
                :key="isho.id"
                :label="isho.value"
                :value="isho.id"
              ></el-option>
            </el-select>
          </el-form-item>

        <el-form-item label="活动链接" prop="link">
          <el-input v-model="form.link"/>
        </el-form-item>

          <el-form-item label="是否启用">
            <el-select v-model="form.enabled" placeholder="请选择是否启用" >
              <el-option
                v-for="isho in isDefaults"
                :key="isho.id"
                :label="isho.value"
                :value="isho.id"
              ></el-option>
            </el-select>
          </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAd, getAd, delAd, addAd, updateAd } from "@/api/popularize/ad";
import OSS from 'ali-oss';

export default {
  name: "Ad",
  data() {
    return {
      // 遮罩层
      loading: true,
      fileList: [], // 初始化为空数组
      // 选中数组
      ids: [],
      isDefaults: [
        { id : 1 , value: '启用'},
        { id : 0 , value: '不启用'}
      ],
      positions: [
        { id : 1 , value: '首页'},
        { id : 2 , value: '分类'}
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 广告表格数据
      adList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "广告标题不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "广告图片不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.initOSSClient();
  },
  methods: {
    handleAvatarSuccess(res, file) {
    // 假设上传成功后，服务器返回的图片 URL 在 res.url 中
    this.form.url = res.url; // 将图片 URL 保存到 form.url
  },

  // 图片上传前的校验
  beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
      this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
    }
    if (!isLt2M) {
      this.$message.error('上传图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
  },

    /** 查询广告列表 */
    getList() {
      this.loading = true;
      listAd(this.queryParams).then(response => {
        this.adList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        link: null,
        url: null,
        position: null,
        content: null,
        startTime: null,
        endTime: null,
        enabled: null,
        addTime: null,
        updateTime: null,
        deleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAd(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改广告";
      });
    },
    async handleImageChange(file, extraParam) {
      if (file) {
        console.log(JSON.stringify(file, null, 2));
        const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
        if (!isImage) {
          this.$message.error('只能上传JPG/PNG格式的图片!');
          return false;
        }

        const isLt3M = file.size / 1024 / 1024 < 3;
        if (!isLt3M) {
          this.$message.error('图片大小不能超过3MB!');
          return false;
        }

        try {
          // 生成更简单的文件名
          const fileName = `product-images/${Date.now()}-${file.name}`;

          console.log('开始上传文件到OSS:', fileName);
          console.log('开始OSS:', file);

          // 使用put方法代替multipartUpload
          const result = await this.ossClient.put(fileName, file);
          console.log('OSS上传结果:', result);

          // 生成可直接访问的URL
          const imageUrl = result.url;
          console.log('生成的文件URL:', imageUrl);

          switch (extraParam) {
              case "url":
                  this.form.url = imageUrl;
                  break;
              default:
                  console.log("未匹配到任何情况");
          }

          // 更新fileList和form.image
          this.fileList.push({
            name: file.name,
            url: imageUrl
          });
          // 确保form.image是对象数组
          this.form.image = this.fileList.map(item => ({
            name: item.name,
            url: item.url
          }));

          console.log('当前fileList:', this.fileList);
          console.log('当前form.image:', this.form.image);

          this.$message.success('图片上传成功');
          return false;
        } catch (error) {
          console.error('上传失败:', error);
          this.$message.error(`上传失败: ${error.message}`);
          return false;
        }
      }
    },
    // 初始化OSS客户端
    initOSSClient() {
      try {
        this.ossClient = new OSS({
          region: 'oss-cn-shenzhen',
          accessKeyId: 'LTAI5tJDNLAHLvTNUxffAYo5',
          accessKeySecret: 'pvXyZSJRoiTEK3HsKms4sk1tzT69Ky',
          bucket: 'jhx-img',
          secure: true,
          // 添加以下配置
          endpoint: 'https://oss-cn-shenzhen.aliyuncs.com',
          cname: false
        });
        console.log('OSS客户端初始化成功');
      } catch (error) {
        console.error('OSS初始化失败:', error);
        this.$message.error('OSS服务初始化失败');
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAd(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除广告编号为"' + ids + '"的数据项？').then(function() {
        return delAd(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/ad/export', {
        ...this.queryParams
      }, `ad_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
